package com.apes.fn.scm.appScan;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.soe.metadata.Scene;
import com.apes.framework.plugin.soe.store.database.repository.SceneRepository;
import com.apes.framework.util.EventUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import com.apes.scm.stock.transfer.model.ConsumableUse;
import com.apes.scm.stock.transfer.model.ConsumableUseItem;
import com.apes.scm.stock.transfer.model.Pick;
import com.apes.scm.stock.transfer.repository.PickRepository;
import com.apes.scm.stock.transfer.service.ConsumableUseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 耗材领用
 */
@Service
public class ConsumableUseTemplate extends SimpleTemplate {

    @Autowired
    private ConsumableUseService consumableUseService;
    @Autowired
    private DeptRepository deptRepository;
    @Autowired
    private LocationRepository locationRepository;
    @Autowired
    private PickRepository pickRepository;

    @Override
    public String[] identifys() {
        return new String[]{"HC0"};
    }

    @Override
    public void submit(SimpleRequest request) {
        String deptId = request.get("DDID");
        Dept dept = deptRepository.findOne(deptId);
        if (dept == null) throw new RuntimeException("部门信息不存在！");

        ConsumableUse consumableUse = new ConsumableUse();
        // 获取操作员
        consumableUse.setClerk(getCreator(request));
        consumableUse.setDept(dept);

        // 设置仓库库区
        String locationId = request.get("CKKQID");
        Location location = locationRepository.findOne(locationId);
        consumableUse.setLocation(location);
        consumableUse.setCompany(location.getCompany());

        // 交货方式
        Enumeration moveType = new Enumeration();
        moveType.setId("one");
        consumableUse.setMoveType(moveType);

        // 场景流
        Scene scene = SpringManager.getBean(SceneRepository.class).findOne("HC000");
        consumableUse.setScene(scene);
        consumableUse.setConsumableUseItems(
                ((JSONArray) request.get("WAR_TMCRKDMX")).stream().map(
                        mx -> {
                            JSONObject mxO = (JSONObject) mx;
                            ConsumableUseItem item = new ConsumableUseItem();
                            item.setUseQty(mxO.getDouble("SMJS"));
                            item.setProduct(getProduct(mxO.getString("SPID")));
                            item.setUom(item.getProduct().getUom());
                            return item;
                        }
                ).collect(Collectors.toSet())
        );
        request.setData(consumableUse);
        consumableUse = consumableUseService.create(request);

        // 审核、生成交货单
        Map map = new HashMap();
        map.put("id", consumableUse.getId());
        map.put("version", consumableUse.getVersion());
        request.setData(map);
        consumableUseService.approve(request);
    }

    /**
     * 耗材交货单发货
     * @param consumableUseId 耗材领用单号
     */
    public void deliver(String consumableUseId) {
        Pick pick = pickRepository.findFirstByOriginAndOriginBusinessType(consumableUseId, ConsumableUse.class.getSimpleName());
        if (pick == null) throw new RuntimeException("未找到有效的交货订单！");
        if (pick.getState().equals("done")) return;
        // 不对bean操作,不然会刷新对象值
        Map pickJO = MapUtil.mapped(pick);
        pickJO.put("pickItems", ((List<Map<String, Object>>) pickJO.get("pickItems")).stream()
                .map(item -> {
                    item.put("qtyDone", item.get("productUomQty"));
                    return item;
                }).collect(Collectors.toList()));
        EventUtil.sendSynEvent(this, "event:stock.pick.pda", pickJO);
    }
}
